/*
 *  This file is part of ZiggyStardust.
 *
 *  ZiggyStardust is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ZiggyStardust is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.wisc.csvParser;

import java.awt.CardLayout;
import java.awt.Color;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;

import java.util.Vector;

import org.apache.log4j.Logger;



/**
 *
 * @author  lawinslow
 */
public class DataChainJPanel extends JPanel
        implements PropertyChangeListener {

    private DataChain datachain;
    private Vector<IStatusPanel> lastPanels;
    private String name = "";

    private Logger logger = Logger.getLogger(DataChainJPanel.class.getName());
    
    /** Creates new form DataChainJPanel
     * 
     * @param chain The underlying DataChain object that this GUI interface represents
     */
    public DataChainJPanel(DataChain chain) {
        initComponents();

        datachain = chain;

        //call update methods to synch display state to object state.
        updateChainList();
        setStartedState(datachain.isStarted());

        datachain.addPropertyChangeListener(this);
        
    }

    public DataChain getDataChain() {
        return datachain;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        chainList = new javax.swing.JList();
        ContentPane = new javax.swing.JPanel();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        moveUpButton = new javax.swing.JButton();
        moveDownButton = new javax.swing.JButton();
        startButton = new javax.swing.JButton();
        stopButton = new javax.swing.JButton();

        chainList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                chainListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(chainList);

        ContentPane.setLayout(new java.awt.CardLayout());

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        removeButton.setLabel("Remove");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        moveUpButton.setText("^");
        moveUpButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveUpButtonActionPerformed(evt);
            }
        });

        moveDownButton.setText("v");
        moveDownButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                moveDownButtonActionPerformed(evt);
            }
        });

        startButton.setText("Start");
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonActionPerformed(evt);
            }
        });

        stopButton.setText("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(moveUpButton)
                            .addComponent(addButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(moveDownButton)
                            .addComponent(removeButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(startButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ContentPane, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startButton)
                    .addComponent(stopButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(removeButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(moveUpButton)
                    .addComponent(moveDownButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(ContentPane, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    
    private void chainListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_chainListValueChanged

        if (evt instanceof javax.swing.event.ListSelectionEvent &&
                chainList.getSelectedValue() instanceof IStatusPanel) {

            CardLayout tmp = (CardLayout) ContentPane.getLayout();
            tmp.show(ContentPane, ((IStatusPanel) chainList.getSelectedValue()).getPanelID());
        }
}//GEN-LAST:event_chainListValueChanged

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed

        FilterPickerDialog d = new FilterPickerDialog(
                (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this), true);
        d.setVisible(true);


        if (d.getReturnStatus() == FilterPickerDialog.RET_OK) {

            try {
                datachain.addIntermediateFilter(
                        DataFilterFactory.getDataFilter(
                        d.getReturnType()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

}//GEN-LAST:event_addButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        if (chainList.getSelectedValue() instanceof IDataRepository) {
            datachain.removeIntermediateFilter(
                    (IDataRepository) chainList.getSelectedValue());
        }
}//GEN-LAST:event_removeButtonActionPerformed

    private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed
        if(chainList.getSelectedValue() instanceof IDataRepository) {
            datachain.moveIntermediateFilter((IDataRepository) chainList.getSelectedValue(), DataChain.direction.UP);
        } else {
            return;
        }
}//GEN-LAST:event_moveUpButtonActionPerformed

    private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed
        if(chainList.getSelectedValue() instanceof IDataRepository) {
            datachain.moveIntermediateFilter((IDataRepository) chainList.getSelectedValue(), DataChain.direction.DOWN);
        } else {
            return;
        }
    }//GEN-LAST:event_moveDownButtonActionPerformed

    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
        internalStart();
    }//GEN-LAST:event_startButtonActionPerformed

    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopButtonActionPerformed
        internalStop();
    }//GEN-LAST:event_stopButtonActionPerformed

    private void internalStart(){
        if(datachain.Start())
            setStartedState(true);
    }
    
    private void internalStop(){
        if(datachain.Stop())
                setStartedState(false);
    }
    


    private void updateChainList() {
        
        if (lastPanels != null) {
            for (IStatusPanel s : lastPanels) {
                ContentPane.remove(s.getStatusJPanel());
            }
        }

        lastPanels = datachain.getObjectChain();
        for (IStatusPanel s : lastPanels) {
            ContentPane.add(s.getStatusJPanel(), s.getPanelID());
        }

        chainList.setListData(lastPanels);
    }
    
    private void setStartedState(boolean isStarted){
        startButton.setEnabled(!isStarted);
        moveUpButton.setEnabled(!isStarted);
        moveDownButton.setEnabled(!isStarted);
        addButton.setEnabled(!isStarted);
        removeButton.setEnabled(!isStarted);
        stopButton.setEnabled(isStarted);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel ContentPane;
    private javax.swing.JButton addButton;
    private javax.swing.JList chainList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton moveDownButton;
    private javax.swing.JButton moveUpButton;
    private javax.swing.JButton removeButton;
    private javax.swing.JButton startButton;
    private javax.swing.JButton stopButton;
    // End of variables declaration//GEN-END:variables
    public class MyCellRenderer extends JLabel implements ListCellRenderer {

        public MyCellRenderer() {
            setOpaque(true);
        }

        @Override
        public java.awt.Component getListCellRendererComponent(
                JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
            setText(value.toString());
            if (value instanceof IDataParser) {
                this.setBackground(
                        ((IDataParser) value).isStarted() ? Color.GREEN : Color.RED);
            } else if (value instanceof IDataRepository) {
                this.setBackground(
                        ((IDataRepository) value).isStarted() ? Color.GREEN : Color.RED);
            } else {
                this.setBackground(Color.GRAY);
            }
            if (isSelected) {
                setBackground(Color.lightGray);
            }
            return this;
        }
    }

    /**
     * Handles the property change events to update the UI display.
     * @param e The property change event.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e){
        if(e.getPropertyName().equalsIgnoreCase("chain")){
            this.updateChainList();
        }else if(e.getPropertyName().equalsIgnoreCase("isrunning") ||
                e.getPropertyName().equalsIgnoreCase("isrunning")){
            this.setStartedState(datachain.isStarted());
        }
    }

}
